#!/usr/bin/env python -OO
# -*- coding: utf-8 -*-

# Copyright © 2008,2009 Trust Digital Technology Laboratory, Shanghai Jiao Tong University.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice (including the next
# paragraph) shall be included in all copies or substantial portions of the
# Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# Author:
#   XING Dong sheng <homer.xing@gmail.com>

from __future__ import with_statement

__all__ = ['installbasic']

import os, sys
import gconf
G = gconf.client_get_default()
import xdg.DesktopEntry
import softwaredependent as D
from softwareindependent import getArch, fileappend, filecontain, TempOwn

def config_gedit():
	#FIXME 检查是否成功
	#保存之前不创建备份；自动保存；每隔1分钟自动保存一次
	G.set_bool('/apps/gedit-2/preferences/editor/save/auto_save',True)
	G.set_int('/apps/gedit-2/preferences/editor/save/auto_save_interval',1)
	G.set_bool('/apps/gedit-2/preferences/editor/save/create_backup_copy',False)
	#突出显示光标所在行
	G.set_bool('/apps/gedit-2/preferences/editor/current_line/highlight_current_line',True)
	#显示行号
	G.set_bool('/apps/gedit-2/preferences/editor/line_numbers/display_line_numbers',True)
	#显示右边距
	G.set_bool('/apps/gedit-2/preferences/editor/right_margin/display_right_margin',True)
	#突出显示匹配的括号
	G.set_bool('/apps/gedit-2/preferences/editor/bracket_matching/bracket_matching',True)
	#自动缩进
	G.set_bool('/apps/gedit-2/preferences/editor/auto_indent/auto_indent',True)
	#字体为Monospace 12
	G.set_bool('/apps/gedit-2/preferences/editor/font/use_default_font',True)
	G.set_string('/apps/gedit-2/preferences/editor/font/editor_font','Monospace 12')
	#插件：Ctrl+T缩进/反缩进、Ctrl+M代码注释、拼写检查
	G.set_list('/apps/gedit-2/plugins/active-plugins',gconf.VALUE_STRING,['indent','codecomment','spell'])
	#打开GB2312编码的文件时不要乱码
	l = G.get_list('/apps/gedit-2/preferences/encodings/auto_detected', gconf.VALUE_STRING)
	if not 'GB2312' in l:
		l.append('GB2312')
		G.set_list('/apps/gedit-2/preferences/encodings/auto_detected', gconf.VALUE_STRING, l)
	l = G.get_list('/apps/gedit-2/preferences/encodings/shown_in_menu', gconf.VALUE_STRING)
	if not 'GB2312' in l:
		l.append('GB2312')
		G.set_list('/apps/gedit-2/preferences/encodings/shown_in_menu', gconf.VALUE_STRING, l)

def config_nautilus():
	#不统计文件夹内文件数、不预播放声音、不预览缩略图、桌面字体是Sans 11、双击可执行文件时用文本编辑器打开、
	G.set_string('/apps/nautilus/preferences/show_directory_item_counts','never')
	G.set_string('/apps/nautilus/preferences/preview_sound','never')
	G.set_string('/apps/nautilus/preferences/show_icon_text','never')
	G.set_string('/apps/nautilus/preferences/show_image_thumbnails','never')
	G.set_int('/apps/nautilus/preferences/thumbnail_limit',1048576)
	G.set_bool('/apps/nautilus/preferences/start_with_toolbar',True)
	G.set_bool('/apps/nautilus/preferences/start_with_sidebar',True)
	G.set_string('/apps/nautilus/preferences/desktop_font','Sans 11')
	G.set_string('/apps/nautilus/preferences/executable_text_activation','display')
	#紧致地排列图标
	G.set_bool('/apps/nautilus/icon_view/default_use_tighter_layout',True)

def config_terminal():
	"黑底白字"
	G.set_bool('/apps/gnome-terminal/profiles/Default/use_theme_colors',False)
	G.set_string('/apps/gnome-terminal/profiles/Default/background_color','#000000000000')
	G.set_string('/apps/gnome-terminal/profiles/Default/foreground_color','#FFFFFFFFFFFF')
	G.set_bool('/apps/gnome-terminal/profiles/Default/silent_bell',True) #don't make a noise when applications send the escape sequence

def config_fontrender():
	#次像素平滑
	G.set_string('/desktop/gnome/font_rendering/hinting','slight')
	G.set_string('/desktop/gnome/font_rendering/antialiasing','rgba')
	#字体改为 Sans 11
	G.set_string('/apps/nautilus/preferences/desktop_font','Sans 11')
	G.set_string('/desktop/gnome/interface/document_font_name','Sans 11')
	G.set_string('/desktop/gnome/interface/font_name','Sans 11')
	G.set_string('/desktop/gnome/interface/monospace_font_name','Monospace 11')
	G.set_string('/apps/metacity/general/titlebar_font','Sans Bold 11')

def addicontopanel():
	#终端图标
	G.set_string('/apps/panel/objects/terminal_icon/menu_path','applications:/')
	G.set_bool('/apps/panel/objects/terminal_icon/locked',False)
	G.set_int('/apps/panel/objects/terminal_icon/position',300)
	G.set_string('/apps/panel/objects/terminal_icon/object_type','launcher-object')
	G.set_bool('/apps/panel/objects/terminal_icon/panel_right_stick',False)
	G.set_bool('/apps/panel/objects/terminal_icon/use_menu_path',False)
	G.set_string('/apps/panel/objects/terminal_icon/launcher_location','/usr/share/applications/gnome-terminal.desktop')
	G.set_string('/apps/panel/objects/terminal_icon/custom_icon','')
	G.set_string('/apps/panel/objects/terminal_icon/tooltip','')
	G.set_string('/apps/panel/objects/terminal_icon/action_type','lock')
	G.set_bool('/apps/panel/objects/terminal_icon/use_custom_icon',False)
	G.set_string('/apps/panel/objects/terminal_icon/attached_toplevel_id','')
	G.set_string('/apps/panel/objects/terminal_icon/bonobo_iid','')
	G.set_string('/apps/panel/objects/terminal_icon/toplevel_id','top_panel_screen0')
	#文本编辑器图标
	G.set_string('/apps/panel/objects/gedit_icon/menu_path','applications:/')
	G.set_bool('/apps/panel/objects/gedit_icon/locked',False)
	G.set_int('/apps/panel/objects/gedit_icon/position',320)
	G.set_string('/apps/panel/objects/gedit_icon/object_type','launcher-object')
	G.set_bool('/apps/panel/objects/gedit_icon/panel_right_stick',False)
	G.set_bool('/apps/panel/objects/gedit_icon/use_menu_path',False)
	G.set_string('/apps/panel/objects/gedit_icon/launcher_location','/usr/share/applications/gedit.desktop')
	G.set_string('/apps/panel/objects/gedit_icon/custom_icon','')
	G.set_string('/apps/panel/objects/gedit_icon/tooltip','')
	G.set_string('/apps/panel/objects/gedit_icon/action_type','lock')
	G.set_bool('/apps/panel/objects/gedit_icon/use_custom_icon',False)
	G.set_string('/apps/panel/objects/gedit_icon/attached_toplevel_id','')
	G.set_string('/apps/panel/objects/gedit_icon/bonobo_iid','')
	G.set_string('/apps/panel/objects/gedit_icon/toplevel_id','top_panel_screen0')
	#加上
	ret = G.get_list('/apps/panel/general/object_id_list',gconf.VALUE_STRING)
	ret += ['gedit_icon','terminal_icon']
	G.set_list('/apps/panel/general/object_id_list',gconf.VALUE_STRING,ret)

def addsysmonitor():
	#系统监视器
	G.set_string('/apps/panel/applets/sysmonitor/action_type','lock')
	G.set_string('/apps/panel/applets/sysmonitor/attached_toplevel_id','')
	G.set_string('/apps/panel/applets/sysmonitor/bonobo_iid','OAFIID:GNOME_MultiLoadApplet')
	G.set_string('/apps/panel/applets/sysmonitor/custom_icon','')
	G.set_string('/apps/panel/applets/sysmonitor/launcher_location','')
	G.set_bool('/apps/panel/applets/sysmonitor/locked',False)
	G.set_string('/apps/panel/applets/sysmonitor/menu_path','applications:/')
	G.set_string('/apps/panel/applets/sysmonitor/object_type','bonobo-applet')
	G.set_bool('/apps/panel/applets/sysmonitor/panel_right_stick',False)
	G.set_int('/apps/panel/applets/sysmonitor/position',500)
	G.set_string('/apps/panel/applets/sysmonitor/tooltip','')
	G.set_string('/apps/panel/applets/sysmonitor/toplevel_id','top_panel_screen0')
	G.set_bool('/apps/panel/applets/sysmonitor/use_custom_icon',False)
	G.set_bool('/apps/panel/applets/sysmonitor/use_menu_path',False)
	G.set_int('/apps/panel/applets/sysmonitor/prefs/size',40)
	G.set_int('/apps/panel/applets/sysmonitor/prefs/speed',1000)
	G.set_string('/apps/panel/applets/sysmonitor/prefs/system_monitor','gnome-system-monitor.desktop')
	G.set_bool('/apps/panel/applets/sysmonitor/prefs/view_cpuload',True)
	G.set_bool('/apps/panel/applets/sysmonitor/prefs/view_diskload',True)
	G.set_bool('/apps/panel/applets/sysmonitor/prefs/view_loadavg',False)
	G.set_bool('/apps/panel/applets/sysmonitor/prefs/view_memload',True)
	G.set_bool('/apps/panel/applets/sysmonitor/prefs/view_netload',True)
	G.set_bool('/apps/panel/applets/sysmonitor/prefs/view_swapload',False)
	#加上
	ret = G.get_list('/apps/panel/general/applet_id_list',gconf.VALUE_STRING)
	ret += ['sysmonitor']
	G.set_list('/apps/panel/general/applet_id_list',gconf.VALUE_STRING,ret)

def fullChineseLanguagePack():
	D.install("language-pack-zh "
"language-pack-gnome-zh "
"language-support-input-zh "
"language-support-fonts-zh "
"language-support-translations-zh "
"language-support-extra-zh")

def fixscim():
	# 修正SCIM输入法突然出错BUG
	D.install("scim-bridge-client-qt")
	#if filecontain("/etc/X11/xinit/xinput.d/zh_CN", "=xim"):
	#	with TempOwn("/etc/X11/xinit/xinput.d/zh_CN") as o:
	#		with open("/etc/X11/xinit/xinput.d/zh_CN", "r+") as f:
	#			content = f.read()
	#			f.seek(0,0) #定位到文件开头
	#			f.write(content.replace("=xim", "=scim") )

def codec():
	#FIXME 这个命令不精确
	D.install("gstreamer0.10-fluendo-mp3") #mp3
	D.install("gstreamer0.10-ffmpeg gstreamer0.10-plugins-bad gstreamer0.10-plugins-bad-multiverse gstreamer0.10-plugins-ugly gstreamer0.10-plugins-ugly-multiverse") #other types

	if getArch()!=64:
		D.install("libstdc++5") #needed by w32codecs.
		f=D.download("wcodecs32")
		D.execute("sudo dpkg --install --force-all %s"%f)
	else:
	#FIXME Conflict: usr/lib/codecs/cook.so
		f=D.download("wcodecs64")
		D.execute("sudo dpkg --install %s"%f)

def vimrc():
	with open(D.HOME+"/.vimrc", "w") as f:
		f.write("syntax on\nset autoindent\nset number\nset mouse=a\n")

def bashrc():
	#设置bashrc
	#防止重复设置
	path = os.path.join(D.HOME,".bashrc")
	if not filecontain( path , "alias rm='rm -i' #ubuntueasysetuper"):
		fileappend( path , r"""
alias rm='rm -i' #ubuntueasysetuper
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
""")

def cupspdf():
	#FIXME cups-pdf cannot be installed in 9.04
	if D.install("cups-pdf"):
		D.execute("sudo chmod 4755 /usr/lib/cups/backend/cups-pdf") #rwsr-xr-x
		#对于9.04 x86_64，需要修正不能打印成pdf文件的BUG
		path = '/etc/apparmor.d/usr.sbin.cupsd'
		with TempOwn( path ) as o:
			with open( path , "r") as f:
				content = f.readlines()
				for i in range(0, len(content)):
					if content[i].find('/usr/lib/cups/backend/cups-pdf')==0:
						content[i]='/usr/lib/cups/backend/cups-pdf flags=(complain) {\n'
						break
			with open( path , "w") as f:
				for i in range(0, len(content)):
					f.write(content[i])

def adobeflashplayer():
	#	从2008年12月起，从中国大陆到macromedia官方网站上下载flashplugin-nonfree的过程，
	#	可以在一分钟内完成，所以改为直接从官网下载安装flashplugin-nonfree。
	if D.install("flashplugin-nonfree"):
	#	Flash中的中文字符不显示为方框
		D.execute("cd /etc/fonts/conf.d/; sudo mv 49-sansserif.conf 49-sansserif.back")

def readme():
	D.execute("cp %s %s"%(D.FILES, D.DESKTOP) )

def removeUnnecessaryDirectories():
	"建立‘桌面’文件夹的英文符号链接，删除不必要的空目录"
	os.system("ln -s ~/桌面 ~/Desktop")
	os.system("rmdir ~/公共的 2>/dev/null")
	os.system("rmdir ~/模板 2>/dev/null")
	os.system("rmdir ~/视频 2>/dev/null")
	os.system("rmdir ~/图片 2>/dev/null")
	os.system("rmdir ~/文档 2>/dev/null")
	os.system("rmdir ~/音乐 2>/dev/null")
	os.system("rm ~/Examples -rf 2>/dev/null") #Examples链接因为工作时无用，也删除
	os.system("rm ~/examples.desktop -f 2>/dev/null") #9.04的Examples链接删除
	#把目录名改成英文
	fn = os.path.expanduser('~/.config/user-dirs.dirs')
	with open(fn,'w') as f:
		f.write("""XDG_DESKTOP_DIR="$HOME/Desktop/"
XDG_DOWNLOAD_DIR="$HOME/"
XDG_TEMPLATES_DIR="$HOME/"
XDG_PUBLICSHARE_DIR="$HOME/"
XDG_DOCUMENTS_DIR="$HOME/"
XDG_MUSIC_DIR="$HOME/"
XDG_PICTURES_DIR="$HOME/"
XDG_VIDEOS_DIR="$HOME/"
""")
	D.execute("xdg-user-dirs-gtk-update &")

#登录后自动启动Workrave
def workraveautostart():
	fn = os.path.expanduser('~/.config/autostart/workrave.desktop')
	e = xdg.DesktopEntry.DesktopEntry(fn)
	e.set('Type','Application')
	e.set('Encoding','UTF-8')
	e.set('Version','1.0')
	e.set('Name','Workrave')
	e.set('Exec','workrave')
	e.set('X-GNOME-Autostart-enabled','true')
	e.write()

def basicsoftwares():
	D.install("gedit-plugins gnochm rar unrar workrave ntfs-3g vim")
	workraveautostart()
	D.install("p7zip p7zip-rar p7zip-full") #7-zip
	D.install("poppler-data") #evince 中文字体
	D.install("nautilus-open-terminal") #在当前文件夹处打开终端。很方便:)
	if getArch()==64:
		D.install("ia32-libs") #不装此软件则不能执行32位程序

def installbasic():
	removeUnnecessaryDirectories()
	basicsoftwares()
	fullChineseLanguagePack()
	fixscim()
	codec()
	vimrc()
	bashrc()
	cupspdf()
	adobeflashplayer()
	D.install("filezilla")
	readme()
	config_fontrender()
	config_gedit()
	config_nautilus()
	config_terminal()
	addicontopanel()
	addsysmonitor()

if __name__ == "__main__":
	installbasic()
